<?php
namespace Home\Controller;

use Home\Model;
import('Common.Common.taobao_https');

class ItemController extends FuncController
{
	public function _initialize()
	{

		$this->_mod = D('Home/Items');
	
		$this->_cate_mod = D('Home/ItemsCate');
	}


	//ajax 获取cate
	public function getCate()
	{
		if(false === $cate_list = F('cate_list')) {
			$cate_list = D('ItemsCate')->cate_cache();
		}
		$items = array();
		foreach ($cate_list['p'] as $key => $val) {
			// $items[$key]->id = $val["id"];
			// $items[$key]->name = $val["name"];
			array_push($items,array("id"=>$val["id"],"name"=>$val["name"]));
		}

		$this->ajaxReturn(0, '', $items);
	}

	//ajax getitems
	public function getItems()
	{
		$p = I('p', 1, 'intval'); //页码
		$page_size = I('size', 1, 'intval'); //每页记录数
		$sort = I('sort', 'new', 'trim'); //排序
		$status = I('status', 'all', 'trim'); //销售状态		
		$cid = I('cid', '', 'intval');  //分类
		$type = I('type', 'default', 'trim'); //类型
		$so = I('so','','trim'); //搜索

	
		$order = 'ordid asc ';

		switch ($sort) {
			case 'new':
				$order .= ', add_time DESC';
				break;
			case 'price':
				$order .= ', coupon_price ASC';
				break;
			case 'rate':
				$order .= ', coupon_rate ASC';
				break;
			case 'hot':
				$order .= ', volume DESC';
				break;		
			case 'default':
				$order .= ', astime DESC, coupon_rate asc';
				break;	
			
		}
		if ($cid && $cid>0) {
			$id_arr = $this->_cate_mod->get_child_ids($cid, true);
			$where['cate_id'] = array('IN', $id_arr);
		}
		switch ($status) {
			case 'all':
				$where['status'] = "underway";
				break;
			case 'underway':
				$where['status'] = "underway";
				break;
			case 'sellout':
				$where['status'] = "sellout";
				break;
		}
		// if (C('itk_wait_time') == '1') {
		// 	$where['coupon_start_time'] = array('egt', time());
		// } elseif (C('itk_wait_time') == '2') {
		// 	$where['coupon_start_time'] = array('elt', time());
		// }

		$where['coupon_start_time'] = array('elt', time());
		$where['coupon_end_time'] = array('egt', time());
		if (C('itk_index_ems') == '1') {
			$where['ems'] = '1';
		}

		//类型区分
		switch ($type) {
			case 'jiu':
				//9.9包邮
					//2018-07-04
				$where['coupon_price'] = array('gt', 0);
				$where['coupon_price'] = array('elt', 10);
				break;
			case 'shijiu':
				//19包邮
				$where['coupon_price'] = array('gt', 10);
				$where['coupon_price'] = array('elt', 20);
				break;
			case 'tehui':
				//特惠
				$where['coupon_rate'] = array('elt', 8000);
				break;
			case 'jx':
				//特惠
				$where['coupon_rate'] = array('elt', 6000);
				break;
			case 'large':
				//大额券
				$where['quan'] = array('egt', 50);
				break;
			case 'today':
				//今日新品
				$where['add_time'] = array('egt', mktime(0,0,0,date('m'),date('d'),date('Y')));
				break;
			case 'default':
				break;
		}

		//判断搜索关键字
		if (isset($so) && !empty($so)) {
			$where['title'] = array('like', '%' . $so . '%');
		}

		$where['pass'] = '1';
		$where['isshow'] = '1';
		$where['isq'] = "1";
		$index_info['sort'] = $sort;
		$index_info['status'] = $status;
		if ($page_size < 1) $page_size = C('itk_index_page_size');
		$index_info['size'] = $page_size;

		$index_info['p'] = $p;


		$start = $page_size * ($p - 1);


		$items_list = $this->_mod->where($where)->order($order)->limit($start . ',' . $page_size)->select();
		$items = array();
		$itemcount = 0;
		foreach ($items_list as $key => $val) {
			//$items[$key]			= $val;
			$items[$key]['title'] = $val["title"];
			$items[$key]['id'] = $val["id"];
			$items[$key]['num_iid'] = $val["num_iid"];
			$items[$key]['shop_type'] = $val["shop_type"];
			$items[$key]['class']	= $this->_mod->status($val['status'],$val['coupon_start_time'],$val['coupon_end_time']);
			$items[$key]['zk'] = round(($val['coupon_price'] / $val['price']) * 10, 1);
			if (!$val['click_url']) {
				$items[$key]['click_url'] = U('Jump/index', array('id' => $val['id']));
			}
			if ($val['coupon_start_time'] > time()) {
				$items[$key]['click_url'] = U('Item/index', array('id' => $val['id']));
				$items[$key]['timeleft'] = $val['coupon_start_time'] - time();
			} else {
				$items[$key]['timeleft'] = $val['coupon_end_time'] - time();
			}
			$items[$key]['cate_name'] = $cate_list['p'][$val['cate_id']]['name']; 
			//$url = C('itk_site_url').U('Item/index',array('id'=>$val['id']));
			$url = U('Item/index', array('id' => $val['id']));
			$items[$key]['url'] = $url;
			$items[$key]['urltitle'] = urlencode($val['title']);
			$items[$key]['price'] = number_format($val['price'], 1);
			//$items[$key]['pic_url'] = urlencode($val['pic_url']);
			$items[$key]['pic_url'] = $val['pic_url'];
			$items[$key]['quan'] = $val["quan"];
			$items[$key]['price'] = $val["price"];
			$items[$key]['coupon_price'] = number_format($val['coupon_price'], 1);
			$itemcount++;
		}
		$count =  $this->_mod->where($where)->count();
		$data['cate_list'] = $cate_list;

		$data['cid'] = $cid;
		$data['items_list'] = $items;
		$data['index_info'] = $index_info;

		$data['item_count'] = $itemcount;
		$data['total_item'] = $count;

		$this->ajaxReturn(0, '', $data);
	}


	//获取详情信息
	public function getDetail()
	{
		$id = I('id', '', 'intval');
		$num_iid = I('num_iid', '', 'intval');
		if(!$num_iid && !$id){ 
			$this->ajaxReturn(1, '', 'args is null.'); 
		}

		if ($id) {
            $item = $this->_mod->where(array('id' => $id))->find();
        } else {
            $item = $this->_mod->where(array('num_iid' => $num_iid))->find();
        }

	

		//判断出售状态
		$item['coupon_status']	= $this->_mod->status($val['status'],$val['coupon_start_time'],$val['coupon_end_time']);

		//判断剩余时间
		if ($val['coupon_start_time'] > time()) {		
			$item['timeleft']  = $val['coupon_start_time'] - time();
		} else {
			$item['timeleft']  = $val['coupon_end_time'] - time();
		}
		
		//判断是否有淘口令
		if (!$item['taotoken']) {
			$apiparams = array(
				'pic' => $item['pic_url'],
				'qurl' => $item['quanurl'],
				'num_iid' => $item['num_iid'],
				'title' => $item['title'],
				'dx' => $item['dx'],
				'turl' => $item['click_url'],
			);
			$item['taotoken'] = $this->transform($apiparams);
			if ($item['taotoken'])
				$this->_mod->where(array('id' => $id))->save(array('taotoken' => $item['taotoken']));
		}


		//处理描述
		$item['desc'] =$this->getProductDesc($item['num_iid']);
		
		//处理small pics:pic_urls
		$smallpics = explode(',', $item['pic_urls']);
		//$this->assign('smallpics', $smallpics);
		$item['smallpics'] = $smallpics;
		$item['isHavPics']= strlen($item['pic_urls'])>0;
		   
		// 2018.01.03
		// 是否开启自动转链接
		// if(C('itk_auto_privilege') ==1 && !$item['click_url']){
		// 	$qUrl=htmlspecialchars_decode($item['quanurl']);
		// 	$geturl = parse_url($qUrl);
		// 	$paramid = convertUrlQuery($geturl['query']);
		// 	$item['click_url'] = autoPrivilege($item['id'],$item['num_iid'] , $paramid['activityId'] == '' ? $paramid['activity_id']:$paramid['activityId'] );
		// }
		// 6.30 新增高效链接跳转
		//$item['ulandUrl'] = $item['click_url'] ? urlencode($item['click_url']) : urlencode(buildUland($item['num_iid'], $item['quanurl'], $item['dx']));

		$item['after_price'] = $item['coupon_price'] - $item['quan'];
		$this->assign('item', $item);
		$this->ajaxReturn(0, '', $item);
	}


	//获取商品描述
	private function getProductDesc($num_iid)
	{
		$infoUrl = 'http://hws.m.taobao.com/cache/mtop.wdetail.getItemDescx/4.1/?data=%7B%22item_num_id%22%3A%22' . $num_iid . '%22%7D';
		$taobao_https = new \taobao_https();
		$taobao_https->fetch($infoUrl);
		$source = $taobao_https->results;
		$comlist = json_decode($source, true);
		$isGetDesc = false;
		if (is_array($comlist)) {
			if ($comlist[ret][0] == 'SUCCESS::接口调用成功') {
				$isGetDesc = true;
			}
		}
		if (!$isGetDesc) {
			$UserAgent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506; .NET CLR 3.5.21022; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';
			$curl = curl_init();
			curl_setopt($curl, CURLOPT_URL, $infoUrl);
			curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
			curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1);
			curl_setopt($curl, CURLOPT_HEADER, 0);
			curl_setopt($curl, CURLOPT_USERAGENT, $UserAgent);
			curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
			$data = curl_exec($curl);
			$comlist = json_decode($data, true);
			if (is_array($comlist)) {
				if ($comlist[ret][0] == 'SUCCESS::接口调用成功') {
					$isGetDesc = true;
				}
			}
		}

		if ($isGetDesc) {
			return $comlist['data']['images'];
			//$tm = $comlist['data']['images'];
			// $onepic = '<img class="lazy" src=' . $tm[0] . '>';
		
			// $desc = implode('', $tm);
			// foreach ($tm as $sms) {
			// 	if (strpos(	$desc, $sms)) {
			// 		$imgurl = '<img class="lazy" src=' . $sms . '>';
			// 		$item['desc'] = str_replace($sms, $imgurl,$desc);
			// 		$item['desc'] = str_replace($tm[0], '',$desc);
			// 	}
			// }
			// $desc = $onepic . '' . 	$desc;
			// return $desc;
		}			
		return '';
	}


	/**
	 * 调用api获取佣金淘口令
	 */
	private function transform($aprams)
	{

		$tb_top = $this->_get_taobao_top();
		$req = $tb_top->load_api("TbkTpwdCreateRequest");		
		//$req->setUserId("123");
		$req->setText($aprams['title']);
		$req->setUrl($aprams['qurl']);
		$req->setLogo($aprams['pic']);
		//$req->setExt("{}");


		$resp = $tb_top->execute($req);
		return $resp->data->model;
		// $taodianjin = C('itk_taojindian_html');
		// if (strpos($taodianjin, "text/javascript")) {
		// 	$pid = get_word($taodianjin, 'pid: "' , '"');
		// } else {
		// 	$pid = $taodianjin;
		// }
		// // 不走定向时 默认鹊桥推广
		// if($aprams['dx'] != 1 && C('itk_queqiao_pid')!=''){
		// 	$pid = C('itk_queqiao_pid');
		// }		
		// if (!$pid) {
		// 	return;
		// }
		// $aprams['pid']=$pid;
		// $tb_top = $this->_get_itk_top();
		// $req = $tb_top->load_api('ItaokeTaotokenRequest');
		// $req->setFields($aprams);				// 设置采集数据分类ID
		// $resp = (array)$tb_top->execute($req);
		// if($resp['status'] != '0000')
		// {
		// 	return;
		// }
		// return $resp['data'];
	}
	/**
	 * 爱淘客开放平台
	 */
	private function _get_taobao_top()
	{
		vendor('taobao.TopClient');    /*vendor('Itaoke.TopClient');*/
		vendor('taobao.RequestCheckUtil');   /*vendor('Itaoke.RequestCheckUtil');*/
		vendor('taobao.Logger');   /*vendor('Itaoke.Logger');*/
		$tb_top = new \TopClient;
		$tb_top->appkey = "24927198";
		$tb_top->secretKey = "a4ed452bf6abf880df07ce6a80e4133c";
		return $tb_top;
	}
}